import { useState, useRef, useEffect } from 'react';
import styles from './login.module.css';

const Login = () => {
  const [sliderPosition, setSliderPosition] = useState(0);
  const [isDragging, setIsDragging] = useState(false);
  const [isVerified, setIsVerified] = useState(false);
  const [puzzleOffset, setPuzzleOffset] = useState(null); // 拼图缺口位置
  const sliderRef = useRef(null);
  const containerRef = useRef(null);
  const puzzleBoxRef = useRef(null);

  // 生成随机的拼图缺口位置
  useEffect(() => {
    if (!puzzleOffset) {
      // 随机生成拼图缺口的水平位置 (40-80% 的宽度范围内)
      const generateRandomOffset = () => {
        if (containerRef.current) {
          const containerWidth = containerRef.current.offsetWidth;
          const min = Math.floor(containerWidth * 0.4);
          const max = Math.floor(containerWidth * 0.8);
          return Math.floor(Math.random() * (max - min)) + min;
        }
        return 200; // 默认值
      };

      setPuzzleOffset(generateRandomOffset());
    }
  }, [puzzleOffset]);


  // 处理鼠标按下事件
  const handleMouseDown = (e) => {
    if (isVerified) return;
    setIsDragging(true);
  };

  // 处理鼠标移动事件
  const handleMouseMove = (e) => {
    if (!isDragging || isVerified) return;

    const containerRect = containerRef.current.getBoundingClientRect();
    const sliderWidth = sliderRef.current.offsetWidth;
    const containerWidth = containerRef.current.offsetWidth;
    const maxOffset = containerWidth - sliderWidth;

    let newPosition = e.clientX - containerRect.left - sliderWidth / 2;
    newPosition = Math.max(0, Math.min(newPosition, maxOffset));

    setSliderPosition(newPosition);

    // 更新拼图背景位置，确保拼图块与背景图片完美匹配
    if (puzzleBoxRef.current) {
      // 拼图块的背景位置应该保持不变，与主背景图对齐
      puzzleBoxRef.current.style.backgroundPosition = `-${puzzleOffset}px center`;
    }

    // 在滑动过程中实时验证
    const puzzleWidth = 40; // 拼图宽度
    const allowedError = containerWidth * 1; // 减小误差范围，使验证更精确

    // 计算滑块位置与拼图缺口的距离
    const distance = Math.abs(newPosition - (puzzleOffset - puzzleWidth / 2));
    const isCorrect = distance < allowedError;

    if (isCorrect && !isVerified) {
      setIsVerified(true);
      // 成功时添加动画效果
      if (puzzleBoxRef.current) {
        puzzleBoxRef.current.classList.add(styles["success-animation"]);
      }
      // 显示成功提示
      setTimeout(() => {
        console.log('验证成功！');
      }, 300);
      setIsDragging(false);
    }
  };

  // 添加共用函数处理震动效果
  const addShakeEffect = () => {
    if (containerRef.current) {
      containerRef.current.classList.add(styles["shake"]);
      setTimeout(() => {
        containerRef.current.classList.remove(styles["shake"]);
      }, 500);
    }
  };

  // 处理鼠标释放事件
  const handleMouseUp = () => {
    if (!isDragging || isVerified) return;

    // 如果没有验证成功，保持滑块在当前位置，只添加震动效果
    if (!isVerified) {
      // 使用共用函数添加震动效果
      addShakeEffect();
    }

    setIsDragging(false);
  };

  // 处理触摸事件（移动端支持）
  const handleTouchStart = () => {
    if (isVerified) return;
    setIsDragging(true);
  };

  const handleTouchMove = (e) => {
    if (!isDragging || isVerified) return;

    const touch = e.touches[0];
    const containerRect = containerRef.current.getBoundingClientRect();
    const sliderWidth = sliderRef.current.offsetWidth;
    const containerWidth = containerRef.current.offsetWidth;
    const maxOffset = containerWidth - sliderWidth;

    let newPosition = touch.clientX - containerRect.left - sliderWidth / 2;
    newPosition = Math.max(0, Math.min(newPosition, maxOffset));

    setSliderPosition(newPosition);

    // 在滑动过程中实时验证
    const puzzleWidth = 40; // 拼图宽度
    const allowedError = containerWidth * 0.01; // 减小误差范围，使验证更精确

    // 计算滑块位置与拼图缺口的距离
    const distance = Math.abs(newPosition - (puzzleOffset - puzzleWidth / 2));
    const isCorrect = distance < allowedError;

    if (isCorrect && !isVerified) {
      setIsVerified(true);
      // 成功时添加动画效果
      if (puzzleBoxRef.current) {
        puzzleBoxRef.current.classList.add(styles["success-animation"]);
      }
      // 显示成功提示
      setTimeout(() => {
        console.log('验证成功！');
      }, 300);
      setIsDragging(false);
    }
  };

  const handleTouchEnd = () => {
    if (!isDragging || isVerified) return;

    // 如果没有验证成功，保持滑块在当前位置，只添加震动效果
    if (!isVerified) {
      // 使用共用函数添加震动效果
      addShakeEffect();
    }

    setIsDragging(false);
  };

  // 重置验证
  const resetVerification = () => {
    setIsVerified(false);
    setSliderPosition(0);
    setPuzzleOffset(null); // 重新生成拼图位置
  };

  // 添加和移除事件监听器
  useEffect(() => {
    if (isDragging) {
      document.addEventListener('mousemove', handleMouseMove);
      document.addEventListener('mouseup', handleMouseUp);
      document.addEventListener('touchmove', handleTouchMove);
      document.addEventListener('touchend', handleTouchEnd);
    } else {
      document.removeEventListener('mousemove', handleMouseMove);
      document.removeEventListener('mouseup', handleMouseUp);
      document.removeEventListener('touchmove', handleTouchMove);
      document.removeEventListener('touchend', handleTouchEnd);
    }

    return () => {
      document.removeEventListener('mousemove', handleMouseMove);
      document.removeEventListener('mouseup', handleMouseUp);
      document.removeEventListener('touchmove', handleTouchMove);
      document.removeEventListener('touchend', handleTouchEnd);
    };
  }, [isDragging, isVerified]);

  return (
    <div className={styles["login-container"]}>
      <h1>Login Page</h1>

      <div className={styles["form-group"]}>
        <label>用户名</label>
        <input type="text" placeholder="请输入用户名" />
      </div>

      <div className={styles["form-group"]}>
        <label>密码</label>
        <input type="password" placeholder="请输入密码" />
      </div>

      <div className={styles["verification-container"]}>
        <div className={styles["puzzle-container"]} ref={containerRef}>
          {/* 背景图片 */}
          <div className={styles["puzzle-background"]}>
            {/* 拼图缺口 */}
            {puzzleOffset && (
              <div
                className={styles["puzzle-hole"]}
                style={{ left: `${puzzleOffset}px` }}
              ></div>
            )}
          </div>

          {/* 拼图滑块 */}
          {puzzleOffset && (
            <div
              className={`${styles["puzzle-piece"]} ${isVerified ? styles["verified"] : ''}`}
              style={{ transform: `translateX(${sliderPosition}px)` }}
              ref={puzzleBoxRef}
            ></div>
          )}
        </div>

        {/* 滑动条 */}
        <div className={styles["slider-container"]}>
          <div
            className={`${styles["slider-bg"]} ${isVerified ? styles["verified"] : ''}`}
            style={{ width: `${(sliderPosition / (containerRef.current?.offsetWidth - (sliderRef.current?.offsetWidth || 40))) * 100 || 0}%` }}
          ></div>
          <div
            className={`${styles["slider-button"]} ${isVerified ? styles["verified"] : ''}`}
            ref={sliderRef}
            style={{ transform: `translateX(${sliderPosition}px)` }}
            onMouseDown={handleMouseDown}
            onTouchStart={handleTouchStart}
          >
            {isVerified ? '✓' : '→'}
          </div>
          <div className={styles["slider-text"]}>
            {isVerified ? '验证成功' : '拖动滑块完成拼图'}
          </div>
        </div>
      </div>

      {isVerified && (
        <button className={styles["login-button"]}>登录</button>
      )}

      {isVerified && (
        <button className={styles["reset-button"]} onClick={resetVerification}>重置验证</button>
      )}
    </div>
  );
};

export default Login;